﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ClassicPassWd
{
    /// <summary>
    /// Interaction logic for VirginiaPassword.xaml
    /// </summary>
    public partial class VirginiaPassword : UserControl
    {
        private char[] alphaCharsUpper =
        {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V', 'W', 'X', 'Y', 'Z'
        };

        private char[] alphaCharsLower =
        {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z'
        };

        private char[] str;
        private ArrayList key;

        public VirginiaPassword()
        {
            InitializeComponent();
        }

        private void BoxProclaim_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            BoxPassword.Text = "";

            if (BoxKey.Text != "" && BoxProclaim.Text != "")
                GetPassword();
        }

        private void GetPassword()
        {
            str = BoxProclaim.Text.Replace(" ", "").ToCharArray();
            key = new ArrayList();
            char[] tempKey = BoxKey.Text.Replace(" ", "").ToCharArray();
            for (int i = 0; i < str.Length; i++)
            {
                key.Add(tempKey[i % tempKey.Length]);
            }

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                builder.Append(alphaCharsUpper[((str[i] - 65) + ((char) key[i] - 65)) % 26]);
            }

            BoxPassword.Text = builder.ToString();
        }

        private void BoxKey_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            BoxPassword.Text = "";

            if (BoxKey.Text != "" && BoxProclaim.Text != "")
                GetPassword();
        }


        private void BoxProclaim_OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Space)
            {
                e.Handled = false;
                return;
            }

            e.Handled = new Regex("[^A-Za-z]").IsMatch(GetCharFromKey.KeyChars(e.Key).ToString());
        }
    }
}